package com.kerwin.rolemgt.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kerwin.annotations.RedisGetAndSet;
import com.kerwin.rolemgt.RoleService;
import com.kerwin.rolemgt.entity.Department;
import com.kerwin.rolemgt.entity.Role;
import com.kerwin.rolemgt.mapper.RoleMapper;
import com.kerwin.utils.CRMConstant;
import com.kerwin.utils.JackSonUtil;
import com.sun.deploy.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    /*用来记录日志*/
    private static Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);
    /*用来处理json的*/
    private ObjectMapper objectMapper = JackSonUtil.objectMapper;

   /*去数据库里面查部门*/
    @Resource
    RedisTemplate<String, Object> redisTemplate;

    /*容器里面找不到这个*/
    /*1、因为我没有new那个接口，容器里面没有的  建立那个mapper*/
    /*2、我在取mapper的时候，容器里依然取不到，因为我的文件夹目录层次不对*/
    /*com/kerwin/departmgt/mapper/DepartmentMapper.class*/
    @Resource
    BaseMapper<Department> departMapper;

    @RedisGetAndSet(keyName = CRMConstant.ROLE_DEPART_KEY,clz=Department.class,frontLog ="从redis取出部门参数并返回",behind= "部门信息存入redis")
    public List<Department> findDepart(){
        /*拿到处理redis*/
        /*ValueOperations<String, Object> stringOpera = redisTemplate.opsForValue();
        Object o = stringOpera.get(CRMConstant.ROLE_DEPART_KEY);
        if(Objects.nonNull(o) && o instanceof String){
            String s = String.valueOf(o);
            try {
                List<Department> departments = objectMapper.readValue(s, objectMapper.getTypeFactory().constructParametricType(List.class, Department.class));
                log.info("从redis取出部门参数并返回");
                return departments;

            } catch (JsonProcessingException e) {
                throw new HandlerException(E.JSON_ERROR);
            }

        }*/

        LambdaQueryWrapper<Department> departWrapper = new LambdaQueryWrapper<>();
        /*把这个东西以字符串的形式存进去*/
        List<Department> departments = departMapper.selectList(departWrapper);

       /* *//*往redis里面存*//*
        ObjectMapper objectMapper = JackSonUtil.objectMapper;
        String departJson=null;
        try {
            departJson = objectMapper.writeValueAsString(departments);
        } catch (JsonProcessingException e) {
            throw new HandlerException(E.JSON_ERROR);
        }

        stringOpera.set(CRMConstant.ROLE_DEPART_KEY, departJson, 30, TimeUnit.MINUTES);
        log.info("部门信息存入redis");*/


        /*返回这个部门list*/
        return departments;

    }
    /*添加role进数据库*/
    public void getRole(Role role){

        String[] permArray = role.getPerm();
        String permissions = StringUtils.join(Arrays.asList(permArray), ",");
        role.setRolePermissions(permissions);

        int insert = baseMapper.insert(role);
    }

    @Resource
    RoleMapper roleMapper;

    @Resource
    RoleService roleService;

    @RedisGetAndSet(keyName = CRMConstant.ROLE_DETAILS,clz = Role.class,frontLog = "从redis里取到角色详情返回",behind = "角色的详细信息存到redis里")
    public List<Role>  queryRole(){

        /*这段是核心代码*/
        LambdaQueryWrapper<Role> QueryWrapper = new LambdaQueryWrapper<Role>();
        List<Role> roles = baseMapper.selectList(QueryWrapper);

        /*应该是这里进入了第二次aop*/
        List<Department> depart = roleService.findDepart();
        for (Role role : roles) {
            /*权限信息*/
            String rolePermissions = role.getRolePermissions();
            String[] rolePermissionsArr = rolePermissions.split(",");
            String permNameArrayString = roleMapper.queryByRolePermissions(rolePermissionsArr);
            role.setRolePermissions(permNameArrayString);

            /*部门信息*/
            for (Department department : depart) {
                if(Objects.equals(role.getRoleDepart(), department.getId())){
                    role.setRoleDepart(department.getDepartName());
                }
            }
        }
        return roles;
    }


    /*查询角色名字列表*/
    @RedisGetAndSet(keyName = CRMConstant.ROLE_NAME,clz = Role.class,frontLog = "从redis里面取到角色名字返回",behind = "把角色名字数据放到redis里")
    public List<Role> getRoleName(){
    /*从redis里面拿到 角色数据详情ROLE_DETAILS  从里面剥离 角色名字*/
        /*先判断redis里面有没有数据  ：不用我判断，我直接调用本类方法  放回列表*/
        List<Role> roles = roleService.queryRole();
        /*我只要里面的名字*/
        List<Role> rolesName = new ArrayList<>();
        for (Role role : roles) {
            Role role1 = new Role();
            role1.setId(role.getId());
            role1.setRoleName(role.getRoleName());
            rolesName.add(role1);
        }
        return rolesName;
    }

}
